# !/usr/bin/python3
# -*- coding: utf-8 -*-

"""
测试控制器类
----------------------------------------------------
@Project :   xinhou-openai-framework
@File    :   ToolController.py
@Contact :   sp_hrz@qq.com

@Modify Time      @Author    @Version    @Desciption
------------      -------    --------    -----------
2023/04/16 22:04  peng.shen   v1.0.0     None
"""
from typing import Union, Optional, List

from fastapi import APIRouter, Depends, Header
from loguru import logger
from pydantic.v1 import Required
from sqlalchemy.orm import Session

from apps.api.schema.ResSummaryCallbackSchema import ResSummaryCallbackSchema
from apps.api.schema.SummaryCallbackSchema import SummaryCallbackSchema
from apps.api.schema.ToolSchema import ToolSchema
from xinhou_openai_framework.core.db.DatabaseManager import DatabaseManager
from xinhou_openai_framework.core.exception.GlobalBusinessException import GlobalBusinessException
from xinhou_openai_framework.core.nacos.NacosHttpClientInvoker import OpenaiAdminRemoteService
from xinhou_openai_framework.core.nacos.NacosSdkClientInvoker import RemoteService
from xinhou_openai_framework.core.reponse.R import R
from xinhou_openai_framework.utils.JsonUtil import JsonUtil
from xinhou_openai_framework.utils.ObjDictUtil import ObjectDict
from xinhou_openai_framework.utils.ReqUtil import ReqUtil

api = APIRouter()


@api.post('/api/summary/callback', tags=["测试接口"],
          response_model=ResSummaryCallbackSchema,
          summary="[v5][OpenAI][Tools]测试总结消息队列回调接口",
          description="此接口为总结异步消息回调接口测试")
async def test_summary_callback(
        search: SummaryCallbackSchema,
        tenant_id: Union[int, None] = Header(
            default=Required,
            convert_underscores=False,
            description="租户ID:为接入方的租户唯一ID"
        ),
        classify_id: Union[int, None] = Header(
            default=Required,
            convert_underscores=False,
            description="分类ID:根据分类类型的主键ID，该ID为接入方的 自由对话、拟物、拟人的数据ID"
        ),
        classify_type: Union[str, None] = Header(
            default=Required,
            convert_underscores=False,
            description="分类类型:all=自由对话,prompt=创作对话,role=角色模拟"
        ),
        platform_code: Union[str, None] = Header(
            default=Required,
            convert_underscores=False,
            description="平台编码:pt=孵化平台,wt=群活平台,dt=数字人平台,业务站：zp=招聘,sm=算命"
        )
):
    logger.info("[header]:{}".format({
        "tenant_id": tenant_id,
        "classify_type": classify_type,
        "classify_id": classify_id,
        "platform_code": platform_code
    }))
    logger.info("[body]:{}".format(search.model_dump_json()))
    return R.SUCCESS({"result": "success"})


@api.post('/api/index/index',
          tags=["test"],
          summary="[v5][OpenAI][Tools]测试人工智能助理信息接口[测试接口]",
          description="通过参数模型传递条件查询")
async def index(
        search: ToolSchema,
        tenant_id: Union[int, None] = Header(
            default=Required,
            convert_underscores=False,
            description="租户ID:为接入方的租户唯一ID"
        ),
        classify_id: Union[int, None] = Header(
            default=Required,
            convert_underscores=False,
            description="分类ID:根据分类类型的主键ID，该ID为接入方的 自由对话、拟物、拟人的数据ID"
        ),
        classify_type: Union[str, None] = Header(
            default=Required, convert_underscores=False,
            description="分类类型:all=自由对话,prompt=创作对话,role=角色模拟"
        ),
        platform_code: Union[str, None] = Header(
            default=Required,
            convert_underscores=False,
            description="平台编码:pt=孵化平台,wt=群活平台,dt=数字人平台,业务站：zp=招聘,sm=算命"
        ),
        db: Session = Depends(DatabaseManager().get_session)
):
    logger.info("[header]:{}".format({
        "tenant_id": tenant_id,
        "classify_type": classify_type,
        "classify_id": classify_id,
        "platform_code": platform_code
    }))
    logger.info("[body]:{}".format(search.model_dump_json()))
    res_data = request_tool("xinhou-openai-embedding-svc:8000",
                            "/tool/index/index", [
                                {"tenant-id": 888888},
                                {"classify-type": "role"},
                                {"classify-id": 888888},
                                {"platform-code": "pt"}
                            ], {
                                "username": "zhangsan",
                                "password": "123456"
                            })

    return R.SUCCESS(res_data)


# ===============================

def request_tool(service_url: str, url: str, headers: Optional[List[dict]] = None,
                 body: Optional[dict] = None) -> ObjectDict:
    """
    发送POST请求到指定的服务端点，并处理返回结果。

    Args:
    - service_url (str): 服务的URL地址
    - url (str): 要发送POST请求的端点URL
    - headers (Optional[dict]): 请求头信息，默认为None
    - body (Optional[dict]): POST请求的JSON数据，默认为None

    Returns:
    - dict: 处理后的返回结果(只返回数据结果)

    Raises:
    - GlobalBusinessException: 如果状态码不是200，则引发全局业务异常
    """

    req_util = ReqUtil(service_url)
    logger.info(f"service_url:{service_url}")
    logger.info("service_headers:{}".format(headers))
    logger.info("service_body:{}".format(JsonUtil.object_to_json(body)))
    response = req_util.set_headers(headers).post(url, json=body)
    if response.status_code == 200:
        response_object = response.json()
        logger.info("service_response:{}".format(response_object))
        res_obj = ObjectDict.from_dict(response_object)
        if res_obj.code == 200:
            return res_obj.data
        else:
            raise GlobalBusinessException(res_obj.code, res_obj.msg)
    else:
        raise GlobalBusinessException(response.status_code, response.reason)


if __name__ == '__main__':
    # service_url = "xinhou-openai-embedding-svc:8000"
    service_url = "http://openai-embedding.xinhou.com"
    res_data = request_tool(service_url,
                            "/tool/index/index", [
                                {"tenant_id": 888888},
                                {"classify_type": "role"},
                                {"classify_id": 888888},
                                {"platform_code": "pt"}
                            ], {
                                "username": "zhangsan",
                                "password": "123456"
                            })
